// 使用对象存储常量
const TabBarConfig = {
	ACTIVE_CLASS: 'active',
	BADGE_CLASS: 'tabbar-badge',
	ICON_CLASS: 'tabbar-icon',
	INPUT_CLASS: 'tabbar-input',
	ITEM_CLASS: 'tabbar-item'
}

// 核心逻辑封装
class TabBar {
	constructor(options) {
		this.data = options.data
		this.tabIndex = options.tabIndex || 0
		//this.container = options.container || '#tabbar'
		this.container = document.getElementById(`${options.container || 'tabbar'}`);
		this.onChange = options.onChange || function() {};
		this.init();
	}

	init() {
		this.render()
		this.bindEvents()
	}

	generateTabItem(item, index) {
		const isActive = index == this.tabIndex;
		const iconSrc = isActive ? item.iconPathSelect : item.iconPath
		const checkedAttr = isActive ? 'checked' : '';

		return `<input type="radio" 
					id="tab_${item.id}" 
					name="tabbar" 
					class="${TabBarConfig.INPUT_CLASS}" 
					readonly="readonly" 
					data-index="${index}"
					${checkedAttr}>
				<label for="tab_${item.id}" class="${TabBarConfig.ITEM_CLASS} ${isActive ? TabBarConfig.ACTIVE_CLASS : ''}">
					<img src="${getRootPath() + iconSrc}" class="${TabBarConfig.ICON_CLASS}">
					${item.name}
					${item.unread > 0 ? `<div class="${TabBarConfig.BADGE_CLASS}">${item.unread}</div>` : ''}
				</label>`
	}

	render() {
		const html = this.data.map((item, index) =>
			this.generateTabItem(item, index)
		).join('')
		this.container.innerHTML = html;
		//$(this.container).html(html)
	}

	bindEvents() {
		// $(this.container).on('change', `.${TabBarConfig.INPUT_CLASS}`, (e) => {
		// 	const index = $(e.target).next('label').data('index')
		// 	this.tabIndex = index
		// 	this.onChange(index)
		// 	this.render()
		// })
		this.container.addEventListener('change', (e) => {
			if (e.target && e.target.matches(`.${TabBarConfig.INPUT_CLASS}`)) {
				let index = e.target.dataset.index;
				this.tabIndex = index
				this.onChange(index)
				this.render()
			}
		});
	}

	setActiveItem(index) {
		this.tabIndex = index
		this.render()
	}
}
